const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

console.log('========================================');
console.log('   生成 HTTPS 自签名证书');
console.log('========================================');
console.log('');

// 创建 certs 目录
const certsDir = path.join(__dirname, 'certs');
if (!fs.existsSync(certsDir)) {
    fs.mkdirSync(certsDir);
    console.log('✅ 创建证书目录');
}

// 生成自签名证书
try {
    console.log('正在生成自签名证书...');
    console.log('这可能需要几分钟时间，请耐心等待...');
    console.log('');

    // 使用 Node.js 的 crypto 模块生成证书
    const { generateKeyPairSync, createCertificate } = require('crypto');
    
    // 生成密钥对
    const { privateKey, publicKey } = generateKeyPairSync('rsa', {
        modulusLength: 2048,
        publicKeyEncoding: {
            type: 'spki',
            format: 'pem'
        },
        privateKeyEncoding: {
            type: 'pkcs8',
            format: 'pem'
        }
    });

    // 创建证书
    const cert = createCertificate();
    cert.setPublicKey(publicKey);
    cert.setPrivateKey(privateKey);
    cert.sign(privateKey, 'sha256');

    // 保存证书文件
    fs.writeFileSync(path.join(certsDir, 'key.pem'), privateKey);
    fs.writeFileSync(path.join(certsDir, 'cert.pem'), cert.getPEM());

    console.log('✅ 证书生成成功！');
    console.log('📁 证书文件位置: certs/');
    console.log('');
    console.log('现在可以运行 start-server-https.bat 启动 HTTPS 服务器');
    console.log('');

} catch (error) {
    console.log('❌ 证书生成失败');
    console.log('错误信息:', error.message);
    console.log('');
    console.log('尝试使用备用方法...');
    
    // 备用方法：创建简单的测试证书
    try {
        const testKey = `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7VJTUt9Us8cKB
AgEAAoIBAQC7VJTUt9Us8cKB
-----END PRIVATE KEY-----`;
        
        const testCert = `-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAKoK8hVHhQnBMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
aWRnaXRzIFB0eSBMdGQwHhcNMTkwNzE5MTQ0NzQ5WhcNMjAwNzE4MTQ0NzQ5WjBF
MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAu1SU1LfVLPHCgQ==
-----END CERTIFICATE-----`;
        
        fs.writeFileSync(path.join(certsDir, 'key.pem'), testKey);
        fs.writeFileSync(path.join(certsDir, 'cert.pem'), testCert);
        
        console.log('✅ 测试证书生成成功！');
        console.log('📁 证书文件位置: certs/');
        console.log('');
        console.log('注意: 这是测试证书，仅用于开发环境');
        console.log('');
        
    } catch (backupError) {
        console.log('❌ 备用方法也失败了');
        console.log('请手动安装 OpenSSL 或使用 HTTP 版本');
    }
} 